package com.hong.spring.dao;

import com.hong.spring.entity.User;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

/**
 * @Auther: csh
 * @Date: 2020/8/18 15:04
 * @Description:用户dao层
 */
@Repository
public class UserDao {
    @Autowired
    private HibernateTemplate hibernateTemplate;
    /**
     *
     * 功能描述:查询总条数
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/18 15:31
     */
    public List<User> findAllUserList(){
        return (List <User>) hibernateTemplate.findByExample(new User());
    }
    /**
     *
     * 功能描述:获取总数
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/18 15:30
     */
    public int findAllTotal(){
        String hql = "select count(*) from User as user";
        Long count = (Long) hibernateTemplate.find(hql).listIterator().next();
        return count.intValue();
    }
    /**
     *
     * 功能描述:更新
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/18 15:30
     */
    public int update(User user){
        if(user==null || user.getId()==null){
            return 0;
        }
        hibernateTemplate.update(user);
        return 1;
    }

    public int save(User user){
        if(user==null){
            return 0;
        }
        Serializable save = hibernateTemplate.save(user);
        return save!=null?1:0;
    }

    public User findById(int id) {
        User user = hibernateTemplate.get(User.class, id);
        return user;
    }

}
